<template>
  <div class="app-container">
    <el-card shadow="never">
      <div slot="header" class="clearfix">
        <el-form :inline="true" :model="queryParams" size="small">
          <el-form-item label="试卷标题/编码">
            <el-input
              v-model="queryParams.keyword"
              placeholder="请输入试卷标题或编码"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>

          <el-form-item label="试卷状态">
            <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
              <el-option label="草稿" :value="0" />
              <el-option label="已发布" :value="1" />
              <el-option label="已归档" :value="2" />
            </el-select>
          </el-form-item>

          <el-form-item label="创建时间">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-row :gutter="10" class="mb-10">
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
          >修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
          >删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="info"
            icon="el-icon-document-checked"
            size="mini"
            :disabled="multiple"
            @click="handleRecover"
          >恢复</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-dropdown @command="handleStatusChange" class="ml-10">
            <el-button type="warning" size="mini">
              状态变更<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="0">设为草稿</el-dropdown-item>
              <el-dropdown-item command="1">发布试卷</el-dropdown-item>
              <el-dropdown-item command="2">归档试卷</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </el-col>
        <el-col :span="1.5">
          <el-dropdown @command="handleExport" class="ml-10">
            <el-button type="success" size="mini">
              导出<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="pdf">导出为PDF</el-dropdown-item>
              <el-dropdown-item command="word">导出为Word</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </el-col>
      </el-row>

      <el-table
        v-loading="loading"
        :data="paperList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="ID" prop="id" width="80" align="center" />
        <el-table-column label="试卷标题" prop="title" min-width="200" />
        <el-table-column label="试卷编码" prop="code" width="120" align="center" />
        <el-table-column label="总分" prop="totalScore" width="80" align="center" />
        <el-table-column label="题目数" prop="questionCount" width="80" align="center" />
        <el-table-column label="知识点数" prop="knowledgePointCount" width="90" align="center" />
        <el-table-column label="状态" width="100" align="center">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusName(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建人" prop="createByName" width="100" align="center" />
        <el-table-column label="创建时间" prop="createTime" width="160" align="center">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handlePreview(scope.row)"
            >预览</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
            >修改</el-button>
            <el-dropdown @command="handleExportSingle" class="ml-10">
              <el-button size="mini" type="text" icon="el-icon-download">
                导出<i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item :command="{id: scope.row.id, type: 'pdf'}">PDF</el-dropdown-item>
                <el-dropdown-item :command="{id: scope.row.id, type: 'word'}">Word</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 预览对话框 -->
    <el-dialog
      title="试卷预览"
      :visible.sync="previewVisible"
      width="80%"
      top="5vh"
      append-to-body
    >
      <paper-preview
        v-if="previewVisible"
        :paper="previewData"
        ref="paperPreview"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="previewVisible = false">关闭</el-button>
        <el-dropdown @command="handleExport" class="ml-10">
          <el-button type="primary">
            导出试卷<i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="pdf">导出为PDF</el-dropdown-item>
            <el-dropdown-item command="word">导出为Word</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listPaper,
  updateStatus,
  deletePaper,
  recoverPaper,
  exportPaper,
  getPaperDetail,
  previewPaper
} from '@/api/paper2/paper'
import PaperPreview from '../manual/PaperPreview'

export default {
  name: 'PaperList',
  components: { PaperPreview },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 试卷表格数据
      paperList: [],
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyword: undefined,
        status: undefined,
        includeDeleted: false
      },
      // 预览对话框
      previewVisible: false,
      // 预览数据
      previewData: null,
      // 导出选项
      exportOptions: {
        showAnswers: true,
        showOptionAnswers: true,
        showAnalysis: true,
        showKnowledgePoints: true,
        showDifficulty: true
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询试卷列表 */
    getList() {
      this.loading = true

      const params = {
        ...this.queryParams,
        beginTime: this.dateRange && this.dateRange[0],
        endTime: this.dateRange && this.dateRange[1]
      }

      listPaper(params).then(response => {
        this.paperList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 状态标签类型
    getStatusType(status) {
      switch (status) {
        case 0: return 'warning' // 草稿
        case 1: return 'success' // 已发布
        case 2: return 'info'    // 已归档
        default: return ''
      }
    },
    // 状态名称
    getStatusName(status) {
      switch (status) {
        case 0: return '草稿'
        case 1: return '已发布'
        case 2: return '已归档'
        default: return '未知'
      }
    },
    // 重置查询条件
    resetQuery() {
      this.dateRange = []
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        keyword: undefined,
        status: undefined,
        includeDeleted: false
      }
      this.handleQuery()
    },
    // 搜索按钮操作
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    // 新增按钮操作
    handleAdd() {
      this.$router.push('/paper2/manual')
    },
    // 修改按钮操作
    handleUpdate(row) {
      const id = row ? row.id : this.ids[0]
      this.$router.push({ path: '/paper2/manual', query: { id } })
    },
    // 删除按钮操作
    handleDelete() {
      this.$confirm('确定要删除选中的试卷吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return deletePaper(this.ids)
      }).then(() => {
        this.getList()
        this.$message.success('删除成功')
      })
    },
    // 恢复按钮操作
    handleRecover() {
      this.$confirm('确定要恢复选中的试卷吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return recoverPaper(this.ids)
      }).then(() => {
        this.getList()
        this.$message.success('恢复成功')
      })
    },
    // 状态变更
    handleStatusChange(command) {
      const status = parseInt(command)
      const statusName = this.getStatusName(status)

      this.$confirm(`确定要将选中的试卷设为"${statusName}"状态吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return updateStatus(this.ids, status)
      }).then(() => {
        this.getList()
        this.$message.success('状态更新成功')
      })
    },
    // 预览试卷
    handlePreview(row) {
      this.loading = true
      previewPaper(row.id).then(response => {
        this.previewData = response.data
        this.previewVisible = true
      }).finally(() => {
        this.loading = false
      })
    },
    // 导出单个试卷
    handleExportSingle(command) {
      const options = {
        showAnswers: true,
        showOptionAnswers: true,
        showAnalysis: true,
        showKnowledgePoints: true,
        showDifficulty: true
      }
      this.exportPaper(command.id, command.type,options)
    },
    // 导出试卷
    handleExport(command) {
      if (this.ids.length === 0 && !this.previewData) {
        this.$message.warning('请选择要导出的试卷')
        return
      }

      const paperId = this.previewData ? this.previewData.id : this.ids[0]
      const options = this.$refs.paperPreview ?
        this.$refs.paperPreview.previewOptions : this.exportOptions

      this.exportPaper(paperId, command, options)
    },
    // 执行导出
    exportPaper(paperId, exportType, options) {
      const loading = this.$loading({
        lock: true,
        text: '正在生成文件，请稍候...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })

      exportPaper(paperId, exportType, options).then(response => {
        const blob = new Blob([response], {
          type: 'application/octet-stream'
        })
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        if(exportType === 'word') exportType = 'docx'
        link.download = `试卷_${paperId}_${new Date().toLocaleString()}.${exportType}`
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)
      }).finally(() => {
        loading.close()
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.mb-10 {
  margin-bottom: 10px;
}

.ml-10 {
  margin-left: 10px;
}

.fixed-width {
  width: 180px;
}
</style>
